package com.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.constant.MessageConstant;
import com.exception.CustomException;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mapper.MemberMapper;
import com.mapper.OrderMapper;
import com.mapper.OrdersettingMapper;
import com.pageResult.PageResult;
import com.pojo.*;
import com.query.QueryPageBean;
import com.result.Result;
import com.service.CheckGroupService;
import com.service.OrderService;
import com.service.OrdersettingService;
import com.utils.DateUtils;
import org.apache.poi.dev.OOXMLLister;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service(interfaceClass = OrderService.class)
public class OrderServiceImpl implements OrderService{


    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private OrdersettingMapper ordersettingMapper;
    @Autowired
    private OrderMapper orderMapper;


    @Transactional
    @Override
    public Result doOrder(Map map){
        //System.out.println(map.get("setmealId")+""+map.get("sex")+""+map.get("name")+""+map.get("telephone")+""+map.get("validateCode")+""+map.get("idCard")+""+map.get("orderDate"));
        /****获取页面传递过来的日期  并且转换成date类型*/
        Object orderDate = map.get("orderDate");//预约日期
        String s = orderDate.toString();
        Date date=null;
        try {
            date = DateUtils.parseString2Date(s);
        } catch (Exception e) {
            e.printStackTrace();
        }
        /*** 1.通过日期查询t_ordersetting表 里面是否存在该日期 * */
        OrdersettingExample oe=new OrdersettingExample();
        OrdersettingExample.Criteria oec = oe.createCriteria();
        oec.andOrderdateEqualTo(date);
        List<Ordersetting> list = ordersettingMapper.selectByExample(oe);
        Order order=new Order();//订单
        /** 2.存在 则可预约*/
        if(list!=null && list.size()>0){
            /** 3.存在则判断该日期是否已经预约满了 满了则提示一下   */
            Ordersetting setting = list.get(0);
            if (setting.getNumber()!=null && setting.getReservations()!=null && setting.getNumber()==setting.getReservations()){
                //判断该日期是否已经约满（已经约满提示）
                return new Result(false,MessageConstant.ORDER_FULL);
            }
            /** 4.可预约：（存在）  */
                /** 5.是否为会员：通过手机号码查询t_member表 里面是否存在该手机号码 */
                MemberExample me=new MemberExample();
                MemberExample.Criteria mec = me.createCriteria();
                mec.andPhonenumberEqualTo(map.get("telephone").toString());
                List<Member> memberList = memberMapper.selectByExample(me);
                /** 6.是会员 */
                if(memberList!=null && memberList.size()>0){
                    Member member = memberList.get(0);
                    /**是否重复预约：判断是否有重复预约，条件：member_id,orderDate,setmeal_id 查询 t_order里面是否存在该条数据*/
                    OrderExample oee=new OrderExample();
                    OrderExample.Criteria oeec = oee.createCriteria();
                    oeec.andMemberIdEqualTo(member.getId());
                    oeec.andOrderdateEqualTo(date);
                    oeec.andSetmealIdEqualTo(Integer.parseInt(map.get("setmealId").toString()));
                    List<Order> orderList = orderMapper.selectByExample(oee);
                    if(orderList!=null && orderList.size()>0){
                        /**存在：重预预约，提示*/
                        return new Result(false,MessageConstant.ORDER_NOT_CF);
                    }
                    /**不存在:没有重复预约 继续完成预约流程 添加数据到订单表*/
                    order.setMemberId(member.getId());
                    order.setOrderdate(date);
                    order.setOrdertype("微信预约");
                    order.setOrderstatus("未到诊");
                    order.setSetmealId(Integer.parseInt(map.get("setmealId").toString()));
                    orderMapper.insertSelective(order);

                }else{/** 不是会员（不存在则创建） */
                    /**创建会员信息.......*/
                    Member m=new Member();
                    m.setName(map.get("name").toString());
                    m.setSex(map.get("sex").toString());
                    m.setIdcard(map.get("idCard").toString());
                    m.setPhonenumber(map.get("telephone").toString());
                    m.setRegtime(new Date());
                    memberMapper.insertSelective(m);

                    /**继续完成预约流程*/
                    order.setMemberId(m.getId());
                    order.setOrderdate(date);
                    order.setOrdertype(order.ORDER_TYPE);
                    order.setOrderstatus(order.ORDER_STATUS);
                    order.setSetmealId(Integer.parseInt(map.get("setmealId").toString()));
                    orderMapper.insertSelective(order);
                }
                /**最后更新预约设置列表*/
                setting.setReservations(setting.getReservations()+1);
                ordersettingMapper.updateByPrimaryKeySelective(setting);
        }else{
            /**该日期不存在   不可预约：提醒*/
            return new Result(false,MessageConstant.ORDER_NOT_DATE);
        }
        /** 预约成功 返回订单id出去*/
        return new Result(true,MessageConstant.ORDER_SUCCESS,order.getId());
    }

    @Override
    public Order findById(Integer id) {
        return orderMapper.queryById(id);
    }

    @Override
    public PageResult selectByQueryString(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize(),true);
        Page<Order> page = orderMapper.queryAll(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public Map<String,Object> queryById(Order order) throws Exception {
        Map<String,Object> map=new HashMap<>();
        Integer memberId = order.getMemberId();
        //查询该订单对应的信息
        Member member = memberMapper.selectByPrimaryKey(memberId);
        map.put("member",member);
        //查询该订单对应的套餐
//        Integer[] setMealId = orderMapper.getSetMealId(memberId);
        Order order1 = orderMapper.selectByPrimaryKey(order.getId());
        map.put("setMealId",order1.getSetmealId());
        map.put("orderdateValue",DateUtils.parseDate2String(order1.getOrderdate()));
        return map;
    }

    @Override
    @Transactional
    public Result add(Member member ,Integer[] SetmealId,String OrderDateValue) throws Exception {
        if(SetmealId!=null && SetmealId.length>0){//必须选择一个套餐没有选择则抛出异常
            /**1.通过选择的日期查询该日期是否已约满*/
            Date date = DateUtils.parseString2Date(OrderDateValue);
            OrdersettingExample oe=new OrdersettingExample();
            OrdersettingExample.Criteria oec = oe.createCriteria();
            oec.andOrderdateEqualTo(date);
            List<Ordersetting> list = ordersettingMapper.selectByExample(oe);
            if(list!=null && list.size()>0) {
                /** 2.存在则判断该日期是否已经预约满了 满了则提示一下*/
                Ordersetting setting = list.get(0);
                if (setting.getNumber() != null && setting.getReservations() != null && setting.getNumber() == setting.getReservations()) {
                    //判断该日期是否已经约满（已经约满提示）
                    return new Result(false, MessageConstant.ORDER_FULL);
                }
                /**可预约*/
                /** 5.是否为会员：通过手机号码查询t_member表 里面是否存在该手机号码 */
                MemberExample me=new MemberExample();
                MemberExample.Criteria mec = me.createCriteria();
                mec.andPhonenumberEqualTo(member.getPhonenumber());
                List<Member> memberList = memberMapper.selectByExample(me);
                /** 6.是会员 */
                if(memberList!=null && memberList.size()>0) {
                    Member member1 = memberList.get(0);
                    /**判断有没有重复预约 通过日期 套餐id 会员id*/
                    List<Order> orderList=null;
                    for (Integer integer : SetmealId) {
                        OrderExample oee=new OrderExample();
                        OrderExample.Criteria oeec = oee.createCriteria();
                        oeec.andMemberIdEqualTo(member1.getId());
                        oeec.andOrderdateEqualTo(date);
                        oeec.andSetmealIdEqualTo(integer);
                        orderList = orderMapper.selectByExample(oee);
                    }
                    if(orderList!=null && orderList.size()>0){
                        /**存在：重预预约，提示*/
                        return new Result(false,MessageConstant.ORDER_NOT_CF);
                    }
                    /**添加订单信息*/
                    for (Integer setMeal : SetmealId) {
                        Order order=new Order();
                        order.setMemberId(member1.getId());
                        order.setOrderdate(date);
                        order.setOrdertype(Order.ORDER_TYPES);
                        order.setOrderstatus(Order.ORDER_STATUS);
                        order.setSetmealId(setMeal);
                        orderMapper.insertSelective(order);
                    }
                }else {/**不是会员/
                    /**添加会员信息*/
                    member.setRegtime(new Date());
                    memberMapper.insertSelective(member);
                    //添加订单信息
                    for (Integer setMeal : SetmealId) {
                        Order order = new Order();
                        order.setMemberId(member.getId());
                        order.setOrderdate(date);
                        order.setOrdertype(Order.ORDER_TYPES);
                        order.setOrderstatus(Order.ORDER_STATUS);
                        order.setSetmealId(setMeal);
                        orderMapper.insertSelective(order);
                    }
                }
                setting.setReservations(setting.getReservations()+1);
                ordersettingMapper.updateByPrimaryKeySelective(setting);
                System.out.println(setting.getId()+"=================="+setting.getNumber());
            }
        }else{
            return  new Result(false,"请选择一个体检套餐");
        }
        return  new Result(true,MessageConstant.ADD_ORDER_SUCCESS);
    }

    @Override
    @Transactional
    public Result update(Member member, Integer SetmealId, String OrderDateValue,Integer id) throws Exception {
            /**1.通过选择的日期查询该日期是否已约满*/
            Date date = DateUtils.parseString2Date(OrderDateValue);
            OrdersettingExample oe=new OrdersettingExample();
            OrdersettingExample.Criteria oec = oe.createCriteria();
            oec.andOrderdateEqualTo(date);
            List<Ordersetting> list = ordersettingMapper.selectByExample(oe);
            if(list!=null && list.size()>0) {
                /** 2.存在则判断该日期是否已经预约满了 满了则提示一下*/
                Ordersetting setting = list.get(0);
                if (setting.getNumber() != null && setting.getReservations() != null && setting.getNumber() == setting.getReservations()) {
                    //判断该日期是否已经约满（已经约满提示）
                    return new Result(false, MessageConstant.ORDER_FULL);
                }
                //判断日期是否没有修改
                Order order1 = orderMapper.selectByPrimaryKey(id);
                if(!DateUtils.parseDate2String(order1.getOrderdate()).equals(DateUtils.parseDate2String(date))){
                    //不相等则修改数量
                    setting.setReservations(setting.getReservations()+1);
                    ordersettingMapper.updateByPrimaryKeySelective(setting);
                }
                //修改会员信息
                memberMapper.updateByPrimaryKeySelective(member);
                //在修改订单信息
                Order order=new Order();
                order.setId(id);
                order.setSetmealId(SetmealId);
                order.setOrderdate(date);
                orderMapper.updateByPrimaryKeySelective(order);

                Date orderdate = order1.getOrderdate();
                OrdersettingExample oe1=new OrdersettingExample();
                OrdersettingExample.Criteria oec1 = oe1.createCriteria();
                oec1.andOrderdateEqualTo(orderdate);
                List<Ordersetting> list1 = ordersettingMapper.selectByExample(oe1);
                if(list1!=null && list1.size()>0) {
                    Ordersetting ordersetting = list1.get(0);
                    if(!DateUtils.parseDate2String(ordersetting.getOrderdate()).equals(DateUtils.parseDate2String(date))){
                        ordersetting.setReservations(ordersetting.getReservations()-1);
                        ordersettingMapper.updateByPrimaryKeySelective(ordersetting);
                    }
                }


            }
            return  new Result(true,MessageConstant.EDIT_ORDER_SUCCESS);
    }

    @Override
    public void updateStatus(Integer id) {
        Order order = orderMapper.selectByPrimaryKey(id);
        order.setOrderstatus("已到诊");
        orderMapper.updateByPrimaryKeySelective(order);
    }


}
